package com.zrf.kafka.main;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Arrays;
import java.util.Properties;

/**
 * @author zhouruifeng
 * @date 2018/5/17
 */
public class KfkConsumer extends Thread {
    private final KafkaConsumer<String, String> consumer;
    private final String topic;
    public KfkConsumer(String topic)
    {
        consumer = new KafkaConsumer(createConsumerConfig());
        this.topic = topic;
    }
    private static Properties createConsumerConfig()
    {
        Properties props = new Properties();
        props.put("bootstrap.servers", KfkConfig.kafkaServerURL);
        props.put("group.id", KfkConfig.groupId);
        props.put("zookeeper.session.timeout.ms", "40000");
        props.put("enable.auto.commit", "true");
        props.put("auto.commit.interval.ms", "1000");
        props.put("zookeeper.sync.time.ms", "200");
        props.put("auto.commit.interval.ms", "1000");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        return props;
    }
    @Override
    public void run() {
        consumer.subscribe(Arrays.asList(topic));
        while (true) {
            ConsumerRecords<String, String> consumerRecords = consumer.poll(100L);
            for (ConsumerRecord<String, String> record : consumerRecords) {
                System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
            }
        }
    }
}
